package com.greenline.push.service.core.send.base;

import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;

import com.greenline.push.core.enums.Channels;
import com.greenline.push.core.enums.MsgSendType;
import com.greenline.push.service.core.item.AppPacket;
import com.greenline.push.service.core.item.Packet;
import com.greenline.push.service.core.tmpl.AppTemplateInfo;
import com.greenline.push.service.core.tmpl.TemplateCache;
import com.greenline.push.service.core.tmpl.freemarker.TemplateRender;
import com.greenline.push.service.core.user.AppUserInfo;
import com.greenline.push.service.core.user.UserConnact;
import com.greenline.push.service.core.user.UserManager;
import com.greenline.push.service.core.utils.Constants;

public class AppPacketBuilder {
    Logger log = Constants.LOG_PROCESS;
    @Resource
    private UserManager userManager;
    private static final String SPLITS = "%";
    @Resource
    private TemplateCache template;
    @Resource
    private TemplateRender templateRender;

    public AppPacket buildChannelPacket(Packet packet, AppTemplateInfo appTempInfo, Channels channel) {
        String methodName = "{AppPacketBuilder.buildChannelPacket}";
        Long userId = packet.getRecvUserId();

        String devieceToken = null;
        // point send should get deviceToken
        if (MsgSendType.POINT.getType() == packet.getType()) {
            if (channel.equals(Channels.apns)) {
                // apns device_token is fetch in apnsSender
                // UserConnact connact = getUserConnact(userId);
                // if (connact == null || connact.getMobile() == null ||
                // connact.getMobile().isEmpty()) {
                // logDeviceToken(JSON.toJSONString(connact));
                // return null;
                // }
                // devieceToken = connact.getMobile();
            } else if (channel.equals(Channels.sms)) {
                // 短信
                UserConnact connact = getUserConnact(userId);
                if (connact == null || connact.getMobile() == null || connact.getMobile().isEmpty()) {
                    logDeviceToken(packet, appTempInfo);
                    return null;
                }
                devieceToken = connact.getMobile();
                // devieceToken = "13291872722";
                log.debug(String.format("%s.sms得到用户:[%s]的token[%s]", methodName, userId, devieceToken));
            } else if (channel.equals(Channels.email)) {
                // 邮箱
                // 如果是群发 ，receiveid会重新获取dosend中判断
                UserConnact connact = getUserConnact(userId);
                if (connact == null || connact.getEmail() == null || connact.getEmail().isEmpty()) {
                    logDeviceToken(packet, appTempInfo);
                    return null;
                }
                devieceToken = connact.getEmail();
                // devieceToken = "zuoshuaiok@126.com";
                log.debug(String.format("%s.email得到用户:[%s]的token[%s]", methodName, userId, devieceToken));
            } else if (channel.equals(Channels.weixin)) {
                // 微信
                AppUserInfo appUserInfo = getAppUser(packet, appTempInfo);
                if (appUserInfo == null || appUserInfo.getDeviceToken() == null || appUserInfo.getDeviceToken().isEmpty()) {
                    logDeviceToken(packet, appTempInfo);
                    return null;
                }
                devieceToken = appUserInfo.getDeviceToken();
                log.debug(String.format("%s.weixin得到用户:[%s]的token[%s]", methodName, userId, devieceToken));
            } else if (channel.equals(Channels.qq)) {
                // qq
                AppUserInfo appUserInfo = getAppUser(packet, appTempInfo);
                if (appUserInfo == null || appUserInfo.getDeviceToken() == null || appUserInfo.getDeviceToken().isEmpty()) {
                    logDeviceToken(packet, appTempInfo);
                    return null;
                }
                devieceToken = appUserInfo.getDeviceToken();
                log.debug(String.format("%s.qq得到用户:[%s]的token[%s]", methodName, userId, devieceToken));
            } else {
                // echat & xmpp
                devieceToken = userId.toString();
            }
        }
        AppPacket appPacket = new AppPacket(packet);
        appPacket.setAppId(appTempInfo.getAppId());
        appPacket.setDeviceToken(devieceToken);// 对应的外部APP的用户ID
        appPacket.setExtTemplId(appTempInfo.getExtTemplId());// 外部的模板ID
        appPacket.setAppTemplateId(appTempInfo.getAppTemplateId());// 本应用模板的db_id
        appPacket.setAppChannelId(appTempInfo.getAppChannelId());// appchannelId

        // 外部参数转化
        String paramConvert = appTempInfo.getParamConvert();
        if (paramConvert != null && !paramConvert.isEmpty() && packet.getParam() != null) {
            Map<String, String> origParam = packet.getParam();

            // Map<String, String> extParams = new HashMap<String, String>();

            String[] params = paramConvert.split(";");
            for (String param : params) {
                String[] keys = param.split(",");
                if (keys.length == 2) {
                    // extParams.put(keys[1], packet.getParam().get(keys[0]));
                    origParam.put(keys[1], origParam.remove(keys[0]));
                }
            }
            appPacket.setExtParam(origParam);
        } else {
            appPacket.setExtParam(packet.getParam());
        }

        // 渲染内容
        if (channel.isNeedRender()) {
            String selfTemplate = appPacket.getTemplateId() + SPLITS + appPacket.getAppTemplateId();
            String context = null;
            if (template.get(selfTemplate) != null) {
                context = templateRender.renderTemplate(selfTemplate, appPacket.getExtParam());
            } else {
                context = templateRender.renderTemplate(appPacket.getTemplateId().toString(), appPacket.getExtParam());
            }
            log.debug(String.format("线程:[%s],freemarker渲染结果:[%s]", Thread.currentThread().getName(), context));
            appPacket.setContext(context);
        }

        return appPacket;
    }

    private void logDeviceToken(Packet packet, AppTemplateInfo info) {
        log.info(String.format("%s:deviceToken不存在.请检查配置.userId:[%s],param:[%s],appId:[%s]", info.getAppChannelId(), packet.getRecvUserId(),
                packet.getParam(), info.getAppId()));
    }

    private UserConnact getUserConnact(Long userId) {
        return userManager.getUserConnact(userId);
    }

    private AppUserInfo getAppUser(Packet packet, AppTemplateInfo appTempl) {
        Long userId = packet.getRecvUserId();
        AppUserInfo appUser = userManager.getAppUserInfo(userId, appTempl.getAppId());
        return appUser;
    }
}
